package com.st.security.controller;

import com.st.security.base.result.STResult;
import com.st.security.exception.CustomException;
import com.st.security.jwt.JwtAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.Map;

/**
 * @创建人: 放生
 * @创建时间: 2022/4/6
 * @描述:
 */
@RestController
public class MainController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping({"/index", "/", ""})
    public String index() {
        return "index";
    }

    // 退出成功会调用这个返回前端 url 要开放出来
    @GetMapping("/api/logout")
    public String logout() {
        return "logout success";
    }

    @GetMapping("/getData")
    public String getData(HttpServletRequest request) {

        HttpSession session = request.getSession();
        // 获取session中所有的键值
        Enumeration<String> attrs = session.getAttributeNames();
        // 遍历attrs中的
        while (attrs.hasMoreElements()) {
            // 获取session键值
            String name = attrs.nextElement().toString();
            // 根据键值取session中的值
            Object vakue = session.getAttribute(name);
            // 打印结果
            System.out.println("------" + name + ":" + vakue + "--------\n");


        }
        return "data";
    }


    // 有'sys:user:add' 或 'sys:user:edit'权限的可以访问
    @PreAuthorize("hasAnyAuthority('sys:user:add','sys:user:edit')")
    @GetMapping(value = {"/need/authority"})
    public String authority() {
        return "good you have authority";
    }

    @PreAuthorize("hasAnyAuthority('sys:user:update')")
    @GetMapping(value = {"/need/auth"})
    public String noAuthority() {
        return "you haven't authority";
    }

    @Resource
    private JwtAuthService jwtAuthService;

    @RequestMapping(value = "/api/authentication")
    public STResult customLogin(@RequestBody Map<String,String> map){
        String username  = map.get("username");
        String password = map.get("password");

        if(StringUtils.isEmpty(username)
                || StringUtils.isEmpty(password)){
            return STResult.build(401,"用户名或者密码不能为空");
        }
        try {
            return STResult.ok((jwtAuthService.login(username, password)));
        }catch (CustomException e){
            return STResult.build(401,"系统出现异常，请联系管理员电话");
        }

    }

    @RequestMapping(value = "/api/refreshtoken")
    public  STResult refresh(@RequestHeader("${jwt.header}") String token){
        return STResult.ok(jwtAuthService.refreshToken(token));
    }

}